package com.example.server;

import com.example.server.util.StringUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author 2
 */
public class ClientController {
    private static boolean thFlag = true;
    private boolean flag = true;
    private Socket socket;
    private PrintWriter out;
    @FXML
    private TextArea textFile;
    @FXML
    private TextField tfip;
    @FXML
    private TextField tfprot;
    @FXML
    private TextArea textArea;

    @FXML
    public void onStartClick() {
        if (flag) {
            new ReceiveThread(textArea, tfip.getText(), tfprot.getText());
        } else {
            textArea.appendText("INFO: 已连接\n");
        }
    }

    @FXML
    public void onSendClick() {
        if (out != null) {
            String text = textFile.getText();
            out.println(text.replaceAll("\\s*", ""));
            textArea.appendText("Client: \n" + text + "\n");
        } else {
            textArea.appendText("ERROR: 没有客户端接入\n");
        }
    }
    public void onFormatClick() {
        String text = textFile.getText();
        textFile.setText(StringUtils.formatJson(text));
    }

    class ReceiveThread extends Thread {
        private final TextArea textArea;
        private final String ip;
        private final int port;
        public ReceiveThread(TextArea textArea, String ip, String port) {
            this.ip = ip;
            this.port = Integer.parseInt(port);
            this.textArea = textArea;
            start();
        }
        @Override
        public void run() {
            try {
                socket = new Socket(ip, port);
            } catch (IOException e) {
                textArea.appendText("ERROR: 未找到服务\n");
            }
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
                textArea.appendText("INFO: 已连接服务\n");
                new SendThread(socket);
                flag = false;
                while (true) {
                    if(!thFlag){
                        break;
                    }
                    textArea.appendText("Server: \n" +StringUtils.formatJson(in.readLine()) + "\n");
                }
            } catch (IOException e) {
                textArea.appendText("ERROR: 未找到服务\n");
            }
        }
    }
    class SendThread extends Thread {
        private final Socket socket;
        public SendThread(Socket socket) {
            this.socket = socket;
            start();
        }
        @Override
        public void run() {
            try {
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

